<?php
/**
 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */
namespace app\api\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Clients\StsClient;
use app\common\constants\CommonConstant;
use app\common\controller\AdminController;
use app\common\service\ZgService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\upload\Uploadfile;
use think\App;
use think\facade\Db;
use app\admin\model\RecycleAgencyConfig;
use app\admin\model\SystemUser;
use think\facade\Cache;
use app\admin\model\RecycleRechargeLog;
use app\admin\model\RecycleUser;
use app\admin\model\RecycleUpload;

/**
 * @ControllerAnnotation(title="公共方法")
 */
class Common extends AdminController
{
    
    use \app\admin\traits\Curd;

    /**
     * 清理缓存接口
     */
    public function clearCache()
    {
        Cache::clear();
        return msg([], 0, "清除缓存成功");
    }

    /**
     * @NodeAnotation(title="小程序路径")
     */
    public function getPages()
    {
        $json_string = file_get_contents(root_path() . "public/json/url.json");
        $url = json_decode($json_string, true);
        
        $keywords = input('keywords');
        if (! empty($keywords)) {
            foreach ($url as $k => $v) {
                if (strpos($v['url'], $keywords) === false && strpos($v['name'], $keywords) === false) {
                    unset($url[$k]);
                }
            }
        }
        $url = array_values($url);

        return msg([   'list' => $url,   'count' => 10], 0, "success");
    }

    /**
     * 根据host(域名)查询OEM代理信息 不需要登录
     * @NodeAnotation(title="查询首页数据")
     */
    public function getProxyByHost()
    {
        $config = sysconfig("site");
        
        return msg($config, 0, "");
    }

    /**
     * @NodeAnotation(title="查询首页数据")
     */
    public function getIndexData()
    {
        $config = sysconfig("site");
        
        return msg($config, 0, "查询成功");
    }

    /**
     * 获取销售额数据
     * @NodeAnotation(title="添加")
     */
    public function getSaleData()
    {
        $request = $this->request;
        $user_id = $this->request->_UID;
        
        $sum_price = 0;
        $sum_count = 0;
        $count_data = [];
        
        if (! empty($count_data)) {
            $sum_count = $count_data['count'];
            $sum_price = $count_data['real_payment'];
        }
        $tg_count = 0;
        $day_tg_count = 0;
        
        $cz_price = RecycleRechargeLog::where("account_id", $user_id)->sum("money");
        $day_cz_price = RecycleRechargeLog::where([
            [
                "account_id",
                "=",
                $user_id
            ],
            [
                "create_time",
                ">",
                strtotime("-1 days")
            ],
            [
                "create_time",
                "<=",
                time()
            ]
        ])->sum("money");
        
        $u_count = RecycleUser::where("account_id", $user_id)->count();
        $day_u_count = RecycleUser::where([
            [
                "account_id",
                "=",
                $user_id
            ],
            [
                "create_time",
                ">",
                strtotime("-1 days")
            ],
            [
                "create_time",
                "<=",
                time()
            ]
        ])->count();
        
        return msg([
            "sum_price" => $sum_price,
            "sum_count" => $sum_count,
            "tg_count" => $tg_count,
            "day_tg_count" => $day_tg_count,
            "cz_price" => $cz_price,
            "day_cz_price" => $day_cz_price,
            "u_count" => $u_count,
            "day_u_count" => $day_u_count
        ], 0, "查询成功");
    }

    /**
     * 获取代理销售额数据
     * @NodeAnotation(title="添加")
     */
    public function getProxySaleData()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        
        $uids = User::where("proxy_id", $merchantId)->field("user_id")
            ->select()
            ->toArray();
        $uids = array_column($uids, "user_id");
        
        $sum_price = 0;
        $sum_count = 0;
        
        $zf_count = 0;
        
        $all_video_count = 0;
        
        $hunjian_count = 0;
        
        return msg([
            "sum_price" => $sum_price,
            "sum_count" => $sum_count,
            "zf_count" => $zf_count,
            "all_video_count" => $all_video_count,
            "hunjian_count" => $hunjian_count
        ], 0, "查询成功");
    }

    /**
     * 获取排名
     * @NodeAnotation(title="添加")
     */
    public function getRankSaleData()
    {
        $request = $this->request;
        
        $type = $request->param("dateType");
        $time = $request->param("datetime");
        $where = [];
        
        if (! empty($time)) {
            $start_time = strtotime($time[0]);
            $end_time = strtotime($time[1]);
            $where[] = [
                [
                    "a.create_time",
                    ">=",
                    $start_time
                ],
                [
                    "a.create_time",
                    "<=",
                    $end_time
                ]
            ];
        } else {
            if ($type == 0) {
                $where[] = [
                    [
                        "a.create_time",
                        ">=",
                        strtotime(date('Y-m-d'))
                    ],
                    [
                        "a.create_time",
                        "<",
                        time()
                    ]
                ];
            } elseif ($type == 1) {
                // 本周
                $start_time = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('y'));
                $where[] = [
                    [
                        "a.create_time",
                        ">=",
                        $start_time
                    ],
                    [
                        "a.create_time",
                        "<",
                        time()
                    ]
                ];
            } elseif ($type == 2) {
                // 本月
                $start_time = mktime(0, 0, 0, date('m'), 1, date('Y'));
                $where[] = [
                    [
                        "a.create_time",
                        ">=",
                        $start_time
                    ],
                    [
                        "a.create_time",
                        "<",
                        time()
                    ]
                ];
            } else 
                if ($type == 3) {
                    // 本年
                    $where[] = [
                        [
                            "a.create_time",
                            ">=",
                            strtotime(date('Y') . "-01" . "-01")
                        ],
                        [
                            "a.create_time",
                            "<",
                            time()
                        ]
                    ];
                }
        }
        
        $buildSql = Db::name("order_goods")->alias("a")
            ->leftJoin("foods b", "a.goods_id=b.id")
            ->where($where)
            ->group("a.goods_id")
            ->field("count(1) value,b.foods_name name,b.foods_img img")
            ->buildSql();
        
        $foods_data = Db::table($buildSql . ' a')->field("*")
            ->order("a.value", "desc")
            ->limit(0, 7)
            ->select();
        
        return msg([
            "foods_data" => $foods_data,
            "video_data" => []
        ], 0, "查询成功");
    }

    /**
     * 获取代理端排名
     * @NodeAnotation(title="添加")
     */
    public function getProxyRankSaleData()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        
        $uids = User::where("proxy_id", $merchantId)->field("user_id")
            ->select()
            ->toArray();
        $uids = array_column($uids, "user_id");
        
        $type = $request->param("dateType");
        $time = $request->param("datetime");
        $where = [
            [
                "a.merchantId",
                "in",
                $uids
            ]
        ];
        if (! empty($time)) {
            $start_time = strtotime($time[0]);
            $end_time = strtotime($time[1]);
            $where[] = [
                [
                    "a.create_time",
                    ">=",
                    $start_time
                ],
                [
                    "a.create_time",
                    "<=",
                    $end_time
                ]
            ];
        } else {
            if ($type == 0) {
                $where[] = [
                    [
                        "a.create_time",
                        ">=",
                        strtotime(date('Y-m-d'))
                    ],
                    [
                        "a.create_time",
                        "<",
                        time()
                    ]
                ];
            } else 
                if ($type == 1) {
                    // 本周
                    $start_time = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('y'));
                    $where[] = [
                        [
                            "a.create_time",
                            ">=",
                            $start_time
                        ],
                        [
                            "a.create_time",
                            "<",
                            time()
                        ]
                    ];
                } else 
                    if ($type == 2) {
                        // 本月
                        $start_time = mktime(0, 0, 0, date('m'), 1, date('Y'));
                        $where[] = [
                            [
                                "a.create_time",
                                ">=",
                                $start_time
                            ],
                            [
                                "a.create_time",
                                "<",
                                time()
                            ]
                        ];
                    } else 
                        if ($type == 3) {
                            // 本年
                            $where[] = [
                                [
                                    "a.create_time",
                                    ">=",
                                    strtotime(date('Y') . "-01" . "-01")
                                ],
                                [
                                    "a.create_time",
                                    "<",
                                    time()
                                ]
                            ];
                        }
        }
        
        $buildSql = User::alias("a")->where("user_id", "in", $uids)
            ->field("a.*,a.earnings value")
            ->buildSql();
        
        $foods_data = Db::table($buildSql . ' a')->field("*")
            ->order("a.value", "desc")
            ->limit(0, 7)
            ->select();
        
        $video_data = VideoLog::alias("a")->leftJoin("user b", "a.merchantId=b.user_id")
            ->field("a.play_count value,a.share_url,b.nickname")
            ->where($where)
            ->order("a.play_count", "desc")
            ->limit(0, 7)
            ->select();
        
        return msg([
            "foods_data" => $foods_data,
            "video_data" => $video_data
        ], 0, "查询成功");
    }

    /**
     * 获取商户收益排 前7名
     * @NodeAnotation(title="添加")
     */
    public function getShRank()
    {
        $data = Db::name("user")->where("tenant_id", 2)
            ->order("earnings", "DESC")
            ->field("*")
            ->limit(0, 7)
            ->select();
        foreach ($data as $k => $v) {
            $v['indexId'] = $k + 1;
            $data[$k] = $v;
        }
        
        return msg($data, 0, "查询成功");
    }

    /**
     * 获取商户收益排 前7名
     * @NodeAnotation(title="添加")
     */
    public function getOemShRank()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        
        $users = User::where("proxy_id", $merchantId)->limit(0, 10)->select();
        foreach ($users as $k => $v) {
            $sh_count = User::where("proxy_id", $v['user_id'])->count();
            $v['value'] = $sh_count;
            $users[$k] = $v;
        }
        return msg($users, 0, "查询成功");
    }

    /**
     * 查询中转账号是否登录
     * @NodeAnotation(title="添加")
     */
    public function checkAccount()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        $account = $request->param("account");
        $password = $request->param("password");
        
        $data = array();
        $data['username'] = $account;
        $data['password'] = $password;
        $response = json_decode(share_wtw_request(CommonConstant::TRANSIT_GET_URL . CommonConstant::TRANSIT_LOGIN_URL, $data, array(
            
            'Content-type: application/json; charset=utf-8'
        )), 
            // 'referer: dczz.admin168.net'
            // 'referer:'.input('server.SERVER_NAME')
            true);
        
        if (! empty($response) && $response["code"] == 2001) {
            
            return msg($response['data'], 0, "");
        } else {
            
            return msg([], 1, "账号验证失败!");
        }
    }

    /**
     * 获取销售额数据 图标
     * @NodeAnotation(title="添加")
     */
    public function getTbSaleData()
    {
        $request = $this->request;
        
        // 销售
        
        $currentTime = time();
        $cyear = floor(date("Y", $currentTime));
        $cMonth = floor(date("1", $currentTime));
        $sql = "";
        for ($i = 0; $i < 12; $i ++) {
            $nMonth = $cMonth + $i;
            $cyear = $nMonth == 0 ? ($cyear - 1) : $cyear; // 年
            $nMonth = $nMonth <= 0 ? 12 + $nMonth : $nMonth; // 月
            $l = strlen($nMonth);
            $nMonth = $l > 1 ? $nMonth : '0' . $nMonth;
            $date = $cyear . "-" . $nMonth;
            if ($i == 0) {
                $start_time = $date;
                $sql .= "(
            SELECT
             '" . $date . "' AS date
            FROM DUAL ";
                continue;
            } else 
                if ($i == 11) {
                    $end_time = $date;
                }
            $sql .= "UNION ALL
            SELECT 
             '" . $date . "' AS date
            FROM DUAL ";
        }
        $sql .= ")";
        
        $subQuery = Order::where([
            [
                "create_time",
                ">=",
                strtotime($start_time)
            ],
            [
                "create_time",
                "<=",
                $end_time
            ],
            [
                "status",
                "=",
                4
            ]
        ])->field("*,DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m') day_time")->buildSql();
        $secondQuery = Db::table($subQuery . ' a')->field("count(1) num,a.day_time")
            ->group('a.day_time')
            ->buildSql();
        $car_data = $this->dateTiaoJoin($secondQuery, $sql, 'value', 'month');
        
        // 转发
        
        $log_data = [];
        
        return msg([
            "car_data" => $car_data,
            "log_data" => $log_data
        ], 0, "查询成功");
    }

    /**
     * 获取代理工作台销售额数据 图标
     * @NodeAnotation(title="添加")
     */
    public function getProxyTbSaleData()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        $uids = User::where("proxy_id", $merchantId)->field("user_id")
            ->select()
            ->toArray();
        $uids = array_column($uids, "user_id");
        
        // 销售
        
        $currentTime = time();
        $cyear = floor(date("Y", $currentTime));
        $cMonth = floor(date("1", $currentTime));
        $sql = "";
        for ($i = 0; $i < 12; $i ++) {
            $nMonth = $cMonth + $i;
            $cyear = $nMonth == 0 ? ($cyear - 1) : $cyear; // 年
            $nMonth = $nMonth <= 0 ? 12 + $nMonth : $nMonth; // 月
            $l = strlen($nMonth);
            $nMonth = $l > 1 ? $nMonth : '0' . $nMonth;
            $date = $cyear . "-" . $nMonth;
            if ($i == 0) {
                $start_time = $date;
                $sql .= "(
            SELECT
             '" . $date . "' AS date
            FROM DUAL ";
                continue;
            } else 
                if ($i == 11) {
                    $end_time = strtotime($date);
                }
            $sql .= "UNION ALL
            SELECT 
             '" . $date . "' AS date
            FROM DUAL ";
        }
        $sql .= ")";
        
        $subQuery = User::where([
            [
                "create_time",
                ">=",
                strtotime($start_time)
            ],
            [
                "create_time",
                "<=",
                $end_time
            ],
            [
                "proxy_id",
                "=",
                $merchantId
            ]
        ])->field("*,DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m') day_time")->buildSql();
        // var_dump($subQuery);
        $secondQuery = Db::table($subQuery . ' a')->field("count(1) num,a.day_time")
            ->group('a.day_time')
            ->order("a.day_time", "desc")
            ->buildSql();
        $car_data = $this->dateTiaoJoin($secondQuery, $sql, 'value', 'month');
        
        // 转发
        $subQueryLog = VideoLog::where([
            [
                "create_time",
                ">=",
                strtotime($start_time)
            ],
            [
                "create_time",
                "<=",
                $end_time
            ],
            [
                "merchantId",
                "in",
                $uids
            ]
        ])->field("*,DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m') day_time")->buildSql();
        $secondQueryLog = Db::table($subQueryLog . ' a')->field("count(1) num,a.day_time")
            ->group('a.day_time')
            ->buildSql();
        $log_data = $this->dateTiaoJoin($secondQueryLog, $sql, 'value', 'month');
        
        return msg([
            "car_data" => $car_data,
            "log_data" => $log_data
        ], 0, "查询成功");
    }

    /**
     * 获取销售额数据 图标
     * @NodeAnotation(title="添加")
     */
    public function getAddShData()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        // 销售
        
        $currentTime = time();
        $cyear = floor(date("Y", $currentTime));
        $cMonth = floor(date("1", $currentTime));
        $sql = "";
        for ($i = 0; $i < 12; $i ++) {
            $nMonth = $cMonth + $i;
            $cyear = $nMonth == 0 ? ($cyear - 1) : $cyear; // 年
            $nMonth = $nMonth <= 0 ? 12 + $nMonth : $nMonth; // 月
            $l = strlen($nMonth);
            $nMonth = $l > 1 ? $nMonth : '0' . $nMonth;
            $date = $cyear . "-" . $nMonth;
            if ($i == 0) {
                $start_time = $date;
                $sql .= "(
            SELECT
             '" . $date . "' AS date
            FROM DUAL ";
                continue;
            } else 
                if ($i == 11) {
                    $end_time = strtotime($date);
                }
            $sql .= "UNION ALL
            SELECT 
             '" . $date . "' AS date
            FROM DUAL ";
        }
        $sql .= ")";
        
        $subQuery = Db::name("user")->where([
            [
                "create_time",
                ">=",
                strtotime($start_time)
            ],
            [
                "create_time",
                "<=",
                $end_time
            ]
        ])
            ->field("*,DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m') day_time")
            ->buildSql();
        $secondQuery = Db::table($subQuery . ' a')->field("count(1) num,a.day_time")
            ->group('a.day_time')
            ->buildSql();
        $car_data = $this->dateTiaoJoin($secondQuery, $sql, 'value', 'month');
        
        // 转发
        
        return msg($car_data, 0, "查询成功");
    }

    /**
     * 获取支付数据
     * @NodeAnotation(title="添加")
     */
    public function getPayData()
    {
        $request = $this->request;
        
        // 取前17天数据
        $end_time = time();
        $dateList = array();
        $sql = "";
        for ($i = 17; $i >= 0; $i --) {
            $date = date('Y-m-d', intval(strtotime('-' . $i . ' day')));
            array_push($dateList, $date);
            if ($i == 17) {
                $start_time = $date;
                $sql .= "(
            SELECT
             '" . $date . "' AS date
            FROM DUAL ";
                continue;
            }
            $sql .= "UNION ALL
            SELECT 
             '" . $date . "' AS date
            FROM DUAL ";
        }
        $sql .= ")";
        
        $subQuery = Order::where([
            [
                "create_time",
                ">=",
                strtotime($start_time)
            ],
            [
                "create_time",
                "<=",
                $end_time
            ],
            [
                "status",
                "=",
                4
            ],
            [
                "merchantId",
                "=",
                $merchantId
            ]
        ])->field("*,DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') day_time")->buildSql();
        $secondQuery = Db::table($subQuery . ' a')->field("count(1) num,a.day_time")
            ->group('a.day_time')
            ->buildSql();
        
        $car_data = $this->dateJoin($secondQuery, $sql);
        
        $t_count = Order::where([
            [
                "status",
                "=",
                4
            ],
            [
                "merchantId",
                "=",
                $merchantId
            ],
            [
                "create_time",
                ">=",
                strtotime($start_time)
            ],
            [
                "create_time",
                "<=",
                time()
            ]
        ])->count();
        
        $d_count = Order::where([
            [
                "status",
                "=",
                4
            ],
            [
                "merchantId",
                "=",
                $merchantId
            ],
            [
                "create_time",
                ">",
                strtotime("-1 days")
            ],
            [
                "create_time",
                "<=",
                time()
            ]
        ])->count();
        
        return msg([
            "count" => $t_count,
            "data" => $car_data,
            "d_count" => $d_count
        ], 0, "查询成功");
    }

    /**
     * 获取视频数据
     * @NodeAnotation(title="添加")
     */
    public function getCurShData()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        /*
         * $start_time = mktime(0,0,0,date('m'),1,date('Y'));
         * $where [] = [
         * ["a.create_time",">=",$start_time],
         * ["a.create_time","<",time()],
         * ["a.tenant_id","=",2]
         * ];
         *
         * $sh_count = Db::name("user")->alias("a")->where($where)->count();
         */
        
        // return msg($sh_count,0,"查询成功");
        $zf_url = $request->domain() . "/mobile/timerCtr/push_video";
        $goods_url = $request->domain() . "/mobile/timerCtr/reload_goods";
        $wait_url = $request->domain() . "/mobile/timerCtr/clearOrder";
        $daili_url = $request->domain() . "/admin/login?loginType=2";
        return msg([
            'zf_url' => $zf_url,
            'goods_url' => $goods_url,
            "wait_url" => $wait_url,
            "daili_url" => $daili_url
        ], 0, "查询成功");
    }

    /**
     * 获取所有打印标签
     * @NodeAnotation(title="添加")
     */
    public function getLabel()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        $labels = CommonLabel::where("merchantId", $merchantId)->select();
        return msg($labels, 0, "");
    }

    /**
     * ription: 获取开发者列表 分页接口
     *
     * @author : twz
     *         @url:
     * @method : GET
     * @return {*}
     */
    public function queryDeveloper()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        try {
            $name = $request->param("name");
            $page = $request->param("page");
            $limit = $request->param("limit");
            
            $type = $request->param("type");
            $where = [];
            
            if (! empty($name)) {
                $where[] = [
                    "a.name",
                    "LIKE",
                    "%" . $name . "%"
                ];
            }
            
            $list = Db::name("developer")->alias("a")
                ->where($where)
                ->limit(($page - 1) * $limit, $limit)
                ->order("a.create_time", "desc")
                ->select();
            $count = Db::name("developer")->alias("a")
                ->where($where)
                ->count();
            
            return msg([
                "list" => $list,
                "count" => $count
            ], 0, "");
        } catch (\Throwable $th) {
            return msg([], 1, "获取数据失败 : " . $th->getMessage());
        }
    }

    /**
     * 新增标签
     */
    public function addLabel()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $post = $this->request->post();
                $count = CommonLabel::where([
                    [
                        "merchantId",
                        "=",
                        $merchantId
                    ],
                    [
                        "label_desc",
                        "=",
                        $post['label_desc']
                    ]
                ])->count();
                if ($count > 0) {
                    return msg([], 1, "新增失败，标签重复");
                }
                
                CommonLabel::insert([
                    "merchantId" => $merchantId,
                    "label_desc" => $post['label_desc']
                ]);
                Db::commit();
                return msg([], 0, "新增成功");
            } catch (\Exception $e) {
                Db::rollback();
                return json([
                    'code' => 1,
                    'msg' => '数据异常:' . $e->getMessage() . " line: " . $e->getLine()
                ]);
            }
        } else {
            return msg([], 1, "请求方式错误");
        }
    }

    /**
     *
     * 新增开发者
     *
     * @param            
     *
     */
    public function addDeveloper()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $post = $this->request->post();
                $id = $post['id'];
                if (! empty($id)) {
                    Db::name("developer")->where("id", $id)->update($post);
                    Db::commit();
                    return msg([], 0, "修改成功");
                } else {
                    $count = Db::name("developer")->where([
                        [
                            "name",
                            "=",
                            $post['name']
                        ]
                    ])->count();
                    if ($count > 0) {
                        return msg([], 1, "新增失败，开发者重复");
                    }
                    Db::name("developer")->insert([
                        "name" => $post['name'],
                        "create_time" => time(),
                        "desc" => $post['desc'],
                        "mobile" => $post['mobile']
                    ]);
                    Db::commit();
                    return msg([], 0, "新增成功");
                }
            } catch (\Exception $e) {
                Db::rollback();
                return json([
                    'code' => 1,
                    'msg' => '数据异常:' . $e->getMessage() . " line: " . $e->getLine()
                ]);
            }
        } else {
            return msg([], 1, "请求方式错误");
        }
    }

    /**
     * 获取视频数据
     * @NodeAnotation(title="添加")
     */
    public function getVideoData()
    {
        $request = $this->request;
        $merchantId = $request->_UID;
        
        // 取前17天数据
        $end_time = time();
        $dateList = array();
        $sql = "";
        $start_time = "";
        for ($i = 17; $i >= 0; $i --) {
            $date = date('Y-m-d', intval(strtotime('-' . $i . ' day')));
            array_push($dateList, $date);
            if ($i == 17) {
                $start_time = $date;
                $sql .= "(
            SELECT
             '" . $date . "' AS date
            FROM DUAL ";
                continue;
            }
            $sql .= "UNION ALL
            SELECT 
             '" . $date . "' AS date
            FROM DUAL ";
        }
        $sql .= ")";
        
        $subQuery = VideoLog::where([
            [
                "create_time",
                ">=",
                strtotime($start_time)
            ],
            [
                "create_time",
                "<=",
                $end_time
            ],
            [
                "merchantId",
                "=",
                $merchantId
            ]
        ])->order("create_time", "desc")
            ->field("*,DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') day_time")
            ->buildSql();
        $secondQuery = Db::table($subQuery . ' a')->field("count(1) num,a.day_time")
            ->group('a.day_time')
            ->buildSql();
        
        $car_data = $this->dateJoin($secondQuery, $sql);
        
        $t_count = VideoLog::where([
            [
                "merchantId",
                "=",
                $merchantId
            ],
            [
                "create_time",
                ">=",
                $start_time
            ],
            [
                "create_time",
                "<=",
                time()
            ]
        ])->count();
        
        $d_count = VideoLog::where([
            [
                "merchantId",
                "=",
                $merchantId
            ],
            [
                "create_time",
                ">=",
                strtotime("-1 days")
            ],
            [
                "create_time",
                "<=",
                time()
            ]
        ])->count();
        
        return msg([
            'd_count' => $d_count,
            "count" => $t_count,
            "data" => $car_data
        ], 0, "查询成功");
    }

    /**
     * 日期连接查询
     *
     * @param sql $subQuery
     *            统计sql
     * @param sql $sql
     *            日期sql
     */
    private function dateJoin($subQuery, $sql)
    {
        $result = Db::table($subQuery . ' a')->rightJoin([
            $sql => 'w'
        ], "a.day_time=w.date")
            ->field("IFNULL(a.num,0) value,w.date date")
            ->order("a.day_time", "desc")
            ->select();
        /*
         * $data = array();
         * foreach ($result as $k=>$v){
         * array_push($data, $v['num']);
         * }
         */
        return $result;
    }

    /**
     * 日期连接查询
     *
     * @param sql $subQuery
     *            统计sql
     * @param sql $sql
     *            日期sql
     */
    private function dateTiaoJoin($subQuery, $sql, $value_name, $date_name)
    {
        $result = Db::table($subQuery . ' a')->rightJoin([
            $sql => 'w'
        ], "a.day_time=w.date")
            ->field("IFNULL(a.num,0) " . $value_name . ",w.date " . $date_name)
            ->order("w.date", "asc")
            ->select();
        /*
         * $data = array();
         * foreach ($result as $k=>$v){
         * array_push($data, $v['num']);
         * }
         */
        return $result;
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function upload()
    {
        $request = $this->request;
        $user_id = $request->_UID;
        $tenant_id = $request->_TENANTID;
        
        $data = [
            'file' => $this->request->file('file')
        ];
        $type = $this->request->param("type");
        $cid = $this->request->param("cid");
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'file|文件' => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}"
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()->setUploadType('local')
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save(null);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            return msg([
                'url' => $upload['url']
            ], 0, "上传成功");
        } else {
            return msg([], 1, "上传失败");
        }
    }

    /**
     * 添加文件到文件库
     * @NodeAnotation(title="添加")
     */
    public function uploadFile()
    {
        $request = $this->request;
        $user_id = $request->_UID;
        $tenant_id = $request->_TENANTID;
        
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file' => $this->request->file('file')
        ];
        $type = $this->request->param("type");
        $cid = $this->request->param("cid");
        
        $uploadConfig = sysconfig('upload');
        
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        
        $rule = [
            'file|文件' => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}"
        ];
        $this->validate($data, $rule);
        try {
            
            $upload = Uploadfile::instance()->setUploadType($uploadConfig['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save([
                "user_id" => $user_id,
                "type" => $type,
                "cid" => $cid,
                "tenant_id" => $tenant_id
            ]);
        } catch (\Exception $e) {
            return msg([], 1, $e->getMessage());
        }
        if ($upload['save'] == true) {
            return msg([
                'url' => $upload['url']
            ], 0, "上传成功");
        } else {
            return msg($upload, 1, "上传失败");
        }
    }

    /**
     * @NodeAnotation(title="添加Pem文件")
     */
    public function uploadPem()
    {
        $type = input('type');
        
        $file = $this->request->file('file');
        // 获取文件后缀
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);
        if (in_array($extension, array(
            "pem"
        ))) {
            $info = $file->move(root_path() . "public/cert/", "apiclient_{$type}." . $extension); // 移动文件到指定目录 没有则创建
            return msg([], 0, "上传成功");
        } else {
            return msg([], 1, "文件格式错误!请上传pem文件");
        }
    }

    public function uploadIntelligencePem()
    {
        $type = input('type');

        $file = $this->request->file('file');
        // 获取文件后缀
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);
        if (in_array($extension, array(
            "pem"
        ))) {
            $info = $file->move(root_path() . "public/intelligence/", "apiclient_{$type}." . $extension); // 移动文件到指定目录 没有则创建

            return msg(['file'=> root_path() . "public/intelligence/". "apiclient_{$type}." . $extension], 0, "上传成功");
        } else {
            return msg([], 1, "文件格式错误!请上传pem文件");
        }
    }

    /**
     * 添加文件到文件库
     * @NodeAnotation(title="添加")
     */
    public function uploadApp()
    {
        $request = $this->request;
        $user_id = $request->_UID;
        $tenant_id = $request->_TENANTID;
        
        $data = [
            'file' => $this->request->file('file')
        ];
        $type = 2;
        $cid = $this->request->param("cid");
        
        // if ($tenant_id == 1) {
        // $uploadConfig = sysconfig('upload');
        // } elseif ($tenant_id == 2) {
        // $uploadConfig = RecycleUpload::where('account_id', $user_id)->find();
        // } elseif ($tenant_id == 3) {
        // $account_id = $request->_USER['account_id'];
        
        // $uploadConfig = RecycleUpload::where('account_id', $account_id)->find();
        // }
        
        $uploadConfig = sysconfig('upload');
        
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        
        $rule = [
            'file|文件' => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}"
        ];
        $this->validate($data, $rule);
        try {
            
            $upload = Uploadfile::instance()->setUploadType($uploadConfig['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save([
                "user_id" => $user_id,
                "type" => $type,
                "cid" => $cid,
                "tenant_id" => $tenant_id
            ]);
        } catch (\Exception $e) {
            return msg([], 1, $e->getMessage());
        }
        if ($upload['save'] == true) {
            return msg([
                'url' => $upload['url']
            ], 0, "上传成功");
        } else {
            return msg($upload, 1, "上传失败");
        }
    }
}